package com.baor.web.controller.mall;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.baor.mall.domain.TBrand;
import com.baor.mall.domain.TCommo;
import com.baor.mall.domain.TLabel;
import com.baor.mall.domain.TTaxonomic;
import com.baor.mall.service.ITCommoService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.baor.common.annotation.Log;
import com.baor.common.core.controller.BaseController;
import com.baor.common.core.domain.AjaxResult;
import com.baor.common.enums.BusinessType;

import com.baor.common.utils.poi.ExcelUtil;
import com.baor.common.core.page.TableDataInfo;

/**
 * 商品管理Controller
 *
 * @author ruoyi
 * @date 2025-07-18
 */
@RestController
@RequestMapping("/mall/shop")
public class TCommoController extends BaseController
{
    @Autowired
    private ITCommoService tCommoService;




    /**
     * 查询商品管理列表
     */
    @PreAuthorize("@ss.hasPermi('mall:shop:list')")
    @GetMapping("/list")
    public TableDataInfo list(TCommo tCommo)
    {
        startPage();
        List<TCommo> list = tCommoService.selectTCommoList(tCommo);
        return getDataTable(list);
    }

    /**
     * 导出商品管理列表
     */
    @PreAuthorize("@ss.hasPermi('mall:shop:export')")
    @Log(title = "商品管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TCommo tCommo)
    {
        List<TCommo> list = tCommoService.selectTCommoList(tCommo);
        ExcelUtil<TCommo> util = new ExcelUtil<TCommo>(TCommo.class);
        util.exportExcel(response, list, "商品管理数据");
    }

    /**
     * 获取商品管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('mall:shop:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(tCommoService.selectTCommoById(id));
    }

    /**
     * 新增商品管理
     */
    @PreAuthorize("@ss.hasPermi('mall:shop:add')")
    @Log(title = "商品管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TCommo tCommo)
    {
        return toAjax(tCommoService.insertTCommo(tCommo));
    }

    /**
     * 修改商品管理
     */
    @PreAuthorize("@ss.hasPermi('mall:shop:edit')")
    @Log(title = "商品管理", businessType = BusinessType.UPDATE)
    @PutMapping("/editcommo")
    public AjaxResult edit(@RequestBody TCommo tCommo)
    {
        return toAjax(tCommoService.updateTCommo(tCommo));
    }

    /**
     * 删除商品管理
     */
    @PreAuthorize("@ss.hasPermi('mall:shop:remove')")
    @Log(title = "商品管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tCommoService.deleteTCommoByIds(ids));
    }

    // 商品标签下拉列表
    @GetMapping("/listLabel")
    public AjaxResult  listLabel() {
        List<TLabel> list = tCommoService.selectTLabelList();
        return success(list);
    }


    //商品品牌下拉列表
    @GetMapping("/listBrand")
    public AjaxResult  listBrand() {
        List<TBrand> list = tCommoService.selectTBrandList();
        return success(list);
    }


    @PutMapping("")
    public String hello() {
        return "hello";
    }


    /**
     * 回收站列表查询
     */
    @PreAuthorize("@ss.hasPermi('mall:shop:recycle')")
    @GetMapping("/list/recycle")
    public TableDataInfo recycleList(TCommo tCommo) {
        startPage();
        List<TCommo> list = tCommoService.selectRecycleBinList(tCommo);
        return getDataTable(list); // 若依TableDataInfo默认code=0
    }

    /**
     * 批量恢复商品
     */
    @PreAuthorize("@ss.hasPermi('mall:shop:restore')")
    @PutMapping("/restore/batch")
    public AjaxResult restoreBatch(@RequestBody Long[] ids) {
        return toAjax(tCommoService.restoreTCommoByIds(ids));
    }

    /**
     * 彻底删除商品
     */
    @PreAuthorize("@ss.hasPermi('mall:shop:forceDelete')")
    @DeleteMapping("/force/{ids}")
    public AjaxResult forceDelete(@PathVariable Long[] ids) {
        return toAjax(tCommoService.forceDeleteTCommoByIds(ids));
    }
    /**
     * 获取商品分类列表（树形）
     */
    @GetMapping("/taxonomicList")
    public AjaxResult getTaxonomicList() {
        List<TTaxonomic> list = tCommoService.selectAllTaxonomic();
        // 确保返回 code=0，data 为树形结构
        return AjaxResult.success(buildTree(list));
    }

    /**
     * 获取商品类型列表
     */
    @GetMapping("/typeList")
    public AjaxResult getTypeList() {
        List<Map<String, Object>> typeList = List.of(
                new HashMap<>() {{ put("value", 0L); put("label", "虚拟商品"); }},
                new HashMap<>() {{ put("value", 1L); put("label", "实物商品"); }}
        );
        // 确保返回 code=0
        return AjaxResult.success(typeList);
    }

    // 构建树形结构（复用原有方法）
    private List<TTaxonomic> buildTree(List<TTaxonomic> taxList) {
        List<TTaxonomic> result = new ArrayList<>();
        for (TTaxonomic tax : taxList) {
            if (tax.getParentId() == 0) {
                result.add(findChildren(tax, taxList));
            }
        }
        return result;
    }

    private TTaxonomic findChildren( @RequestBody TTaxonomic parent,@RequestBody List<TTaxonomic> all) {
        for (TTaxonomic tax : all) {
            if (tax.getParentId().equals(parent.getId())) {
                parent.getChildren().add(findChildren(tax, all));
            }
        }
        return parent;
    }
}
